from django.conf import settings
from django.shortcuts import render

# Create your views here.


# 前端发送一个ajax请求,给后端,参数是用户名
# 获取用户名的个数
# GET:   /users/usernames/(?P < username >\w{5, 20})/count/
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import SKU
from users.models import User, Address
from users.util import generic_active_url, get_active_user
from utils.cart import merge_cookie_to_redis


class RegisterUsernameCountView(APIView):
    def get(self, request, username):
        # 后端接收用户名
        # count=0 表示没有注册
        # count=1 表示已注册
        # 查询校验是否重复
        count = User.objects.filter(username=username).count()
        # 返回响应
        return Response({"count": count, "username": username})


"""
GET /users/phones/(?P<mobile>1[345789]\d{9})/count/
"""


class RegisterPhoneCountAPIView(APIView):
    # 获取手机号
    def get(self, request, mobile):
        # 查询手机号是否存在
        count = User.objects.filter(mobile=mobile).count()
        context = {
            'count': count,
            'phone': mobile
        }
        # 返回响应
        return Response(context)


from rest_framework.mixins import CreateModelMixin
from rest_framework.generics import CreateAPIView, ListCreateAPIView, DestroyAPIView, UpdateAPIView
from users.serializers import RegisterCreateUserSerializer, UserCenterSerializer, UserEmaiSerializer, UpdateSerializer


# CreateAPIView
class RegisterCreateUserView(APIView):
    def post(self, request):
        # 接收参数
        data = request.data
        # 校验参数
        serializers = RegisterCreateUserSerializer(data=data)
        serializers.is_valid(raise_exception=True)
        # 数据入库
        serializers.save()
        # 返回响应
        return Response(serializers.data)


"""
#     登录用户访问个人中心的时候 ,我们需要将个人信息返回获取
#
#     1. 如何确定是登录用户  --> 需要前端传递一个token过来
#     2. 获取用户信息
#     3. 返回数据
#
#     GET     /users/infos/
"""


class UserCenterView(APIView):
    # 设置权限
    permission_classes = [IsAuthenticated]

    def get(self, request):
        # 获取用户信息
        user = request.user
        # 返回数据
        serializer = UserCenterSerializer(user)
        return Response(serializer.data)


"""
用户在点击设置的时候,输入 邮箱信息, 当点击保存的时候 需要将邮箱信息发送给后端


1. 这个接口必须是登录才可以访问
# 2. 接收参数
# 3. 验证数据
# 4. 更新数据
# 5. 发送激活邮件
# 6. 返回响应

PUT         /users/emails/


"""


class UserEmailView(APIView):
    # 设置权限
    permission_classes = [IsAuthenticated]

    def put(self, request):
        # 2. 接收参数
        data = request.data
        # 3. 验证数据
        user = request.user
        serializers = UserEmaiSerializer(user, data=data)
        serializers.is_valid(raise_exception=True)
        # 4. 更新数据
        serializers.save()
        #  5. 发送激活邮件
        from celery_tasks.email.tasks import send_active_email
        send_active_email.delay(data.get('email'), request.user.id)
        # 6. 返回响应
        return Response(serializers.data)


from rest_framework import status


class UserActiveEmailView(APIView):
    """

    当用户点击激活连接的时候,会跳转到一个页面,这个页面中含有 token(含有 用户id和email信息)信息
    前端需要发送一个ajax请求,将 token 发送给后端

    1. 接受token
    2. 对token进行解析
    3. 返回响应

    GET     /users/emails/verification/?token=xxx
    """

    def get(self, request):
        # 1.接受token
        token = request.query_params.get('token')
        if token is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        # 2.对token进行解析
        user = get_active_user(token)
        if user is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        user.email_active = True
        user.save()
        # 3.返回响应
        return Response({'msg': 'ok'})


"""

新增地址功能

前端将用户提交的数据 传递给后端

1.后端接受数据
2.对数据进行校验
3.数据入库
4.返回响应

POST    users/addresses/

"""

from rest_framework.generics import CreateAPIView
from .serializers import AddressSerializer

from rest_framework.viewsets import GenericViewSet  # 笔记用的这个

from rest_framework.generics import GenericAPIView


# 添加地址/显示地址
class AddressCreateAPIView(ListCreateAPIView):
    serializer_class = AddressSerializer
    queryset = Address.objects.all()

    # 查询地址
    def get(self, request, *args, **kwargs):
        user = self.request.user
        serializer = self.get_serializer(self.get_queryset(), many=True)

        # 响应
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 20,
            'addresses': serializer.data,
        })


# 删除地址,修改地址
class AddressDestroyAPIView(DestroyAPIView, UpdateAPIView):
    serializer_class = AddressSerializer
    queryset = Address.objects.all()


class UpdateAPIView(UpdateAPIView):
    serializer_class = UpdateSerializer
    queryset = Address.objects.all()


# 设置默认地址
class AddressStatusAPIView(APIView):
    def put(self, request, id):
        # 获取参数
        address = Address.objects.get(id=id)
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)


"""
String      key:value
Hash        hash_key:   key:value
List        list_key:   value,value,value
Set         set_key:    value4,value2,value10
Zset        zset_key:   value1,value2,value3


history_1: 1,3,5,

# 登录用户才可以请求

一.添加最近浏览
    在详情页面中, 我们去发送一个请求,这个请求中 包含 sku_id,用户信息(JWT)

    # 1. 我们要接收数据, 并且对数据进行校验
    # 2. 把数据保存起来
    # 3. 返回响应

    POST        /users/browerhistories/


二.获取最近浏览
    # 1. 我们区接收数据 (用户信息,以JWT的形式传递)
    # 2. 查询数据
    # 3. 返回响应

    GET     /users/browerhistories/

"""
# APIView
# GenericAPIView                    列表,详情通用支持,一般和mixin配合使用
# CreateAPIView
from .serializers import UserHistorySerializer, SKUSerializer
from django_redis import get_redis_connection


class UserHistoryView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        user = request.user
        # 1. 接收数据, 并且对数据进行校验
        data = request.data
        serializer = UserHistorySerializer(data=data)
        serializer.is_valid(raise_exception=True)
        # 2. 把数据保存起来
        redis_con = get_redis_connection('history')
        # 2.1 获取商品的id
        sku_id = serializer.validated_data.get('sku_id')
        # 2.2去重
        redis_con.lrem('history_%s' % user.id, 0, sku_id)
        # 2.3 保存到redis
        redis_con.lpush('history_%s' % user.id, sku_id)
        # 对列表进行修剪
        redis_con.ltrim('history_%s' % user.id, 0, 4)
        # 3. 返回响应
        return Response(serializer.data)

    def get(self, request):
        # 1. 接收数据 (用户信息,以JWT的形式传递)
        user = request.user
        # 2. 查询数据
        redis_con = get_redis_connection('history')
        sku_ids = redis_con.lrange('history_%s' % user.id, 0, 5)
        # [1,2,3,4,]
        # skus = SKU.objects.filter(id__in=sku_ids)
        # in查询的时候 不会保留原来的顺序
        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            skus.append(sku)

        serializer = SKUSerializer(instance=skus, many=True)
        # serializer.is_valid(raise_exception=True)
        # 3. 返回响应
        return Response(serializer.data)


from rest_framework_jwt.views import ObtainJSONWebToken


class UserAuthorizationView(ObtainJSONWebToken):

    def post(self, request):
        # 调用jwt扩展的方法，对用户登录的数据进行验证
        response = super().post(request)

        # 如果用户登录成功，进行购物车数据合并
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            # 表示用户登录成功
            user = serializer.validated_data.get("user")
            # 合并购物车
            #merge_cart_cookie_to_redis(request, user, response)
            response = merge_cookie_to_redis(request, user, response)

        return response